package com.dede.monochromatism.service

import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import android.os.PersistableBundle
import android.util.Log
import com.dede.applib.extends.getInt
import com.dede.applib.util.LogExtends
import com.dede.applib.util.d
import com.dede.monochromatism.*
import com.dede.monochromatism.db.PackageDb
import com.dede.monochromatism.db.contains
import com.dede.monochromatism.util.Util
import org.jetbrains.anko.defaultSharedPreferences
import org.jetbrains.anko.toast
import java.util.*

/**
 * @author hsh
 * @date 2017/9/26 14:49.
 * @doc
 */
class TimeJobService : JobService(), LogExtends {
    companion object {
        private val JOB_ID_OPEN = 1
        private val JOB_ID_CLOSE = 2

        fun cancelAllJob(context: Context) {
            val scheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
            scheduler.cancelAll()
        }

        fun registerJob(context: Context) {
            val openCalendar = createCalendar(context.getInt(openHour), context.getInt(openMinute))

            val closeCalendar = createCalendar(context.getInt(closeHour), context.getInt(closeMinute))

            val thisCalendar = Calendar.getInstance()

            if (closeCalendar.before(openCalendar)) {//关闭时间在打开时间之前，说明关闭时间应该是第二天
                Log.d("test", "关闭日期+1")
                closeCalendar.add(Calendar.DATE, 1)
            } else if (closeCalendar.timeInMillis == openCalendar.timeInMillis) {
                context.toast("开启和关闭时间相同")
                return
            }

            val scheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler

            val jobInfo = if (!thisCalendar.after(openCalendar)) {
                //当前时间 之前于/相等于（不之后于） 打开时间，延时打开
                val time = openCalendar.timeInMillis - thisCalendar.timeInMillis
                Log.d("test", "open 1 " + time)
                scheduler.cancel(TimeJobService.JOB_ID_OPEN)
                createJobInfo(context, "open", time)
            } else if (!thisCalendar.after(closeCalendar)) {
                //当前时间 之前于/相等于（不之后于） 关闭时间，延时关闭
                val time = closeCalendar.timeInMillis - thisCalendar.timeInMillis
                Log.d("test", "close 2 " + time)
                scheduler.cancel(TimeJobService.JOB_ID_CLOSE)
                createJobInfo(context, "close", time)
            } else {
                openCalendar.add(Calendar.DATE, 1)//第二天打开时间
                val time = openCalendar.timeInMillis - thisCalendar.timeInMillis
                Log.d("test", "open 3 " + time)
                scheduler.cancel(TimeJobService.JOB_ID_OPEN)
                createJobInfo(context, "open", time)
            }

            scheduler.schedule(jobInfo)
        }

        private fun createJobInfo(context: Context, type: String, time: Long): JobInfo {
            val bundle = PersistableBundle()
            bundle.putString("type", type)

            val id = if (type == "open") {
                JOB_ID_OPEN
            } else {
                JOB_ID_CLOSE
            }

            return JobInfo.Builder(id, ComponentName(context, TimeJobService::class.java))
                    .setMinimumLatency(time)
                    .setOverrideDeadline(time)
                    .setExtras(bundle)
                    .setPersisted(true)
                    .build()
        }

        fun createCalendar(hour: Int, minute: Int): Calendar {
            val calendar = Calendar.getInstance()
            calendar.set(Calendar.HOUR_OF_DAY, hour)
            calendar.set(Calendar.MINUTE, minute)
            calendar.set(Calendar.SECOND, 0)
            calendar.set(Calendar.MILLISECOND, 0)
            return calendar
        }

    }

    override fun onStopJob(params: JobParameters?): Boolean {
        return false
    }

    override fun onStartJob(params: JobParameters): Boolean {
        val type = params.extras.getString("type")
        d("onStartJob " + type)
        if (defaultSharedPreferences.getBoolean(S_PRE_STATUS, false)) {
            //多应用支持
            val packageName = PackageChangeListenerServer.getPackageName()
            if (!PackageDb.getIgnoreList().contains(packageName))
                Util.setSimulateColorSpaceState(applicationContext, PackageDb.getOpenList().contains(packageName))
        } else {
            //全部应用
            if (type == "open") {
                toast("开启全色盲")
                Util.setSimulateColorSpaceState(applicationContext, true)
            } else {
                toast("关闭全色盲")
                Util.setSimulateColorSpaceState(applicationContext, false)
            }
        }
        registerJob(applicationContext)//重新注册下一次时间
        return false
    }
}